#include "precomp.h"

namespace Tmpl {

float AABB2f::CollideWithSphereRay(Ray2f& ray, float radius)
{
	Vec2f vSize = Vec2f(radius,radius);
	Vec2f tl = min - vSize;
	Vec2f br = max + vSize;

	// intersect the box with a ray
	Vec2f& dir = ray.GetDir();
	Vec2f& o = ray.GetOrigin();
	const Vec2f r( 1.0f / dir.x, 1.0f / dir.y );
	float tmin = 0.001f, tmax = ray.GetLength();
	for ( int axis = 0; axis < 2; ++axis ) 
	{
		const float t0 = (tl[axis] - o[axis]) * r[axis];
		const float t1 = (br[axis] - o[axis]) * r[axis];
		const float nr = (t0 < t1) ? t0 : t1, fr = (t0 < t1) ? t1 : t0;
		tmin = (tmin < nr) ? nr : tmin, tmax = (fr <  tmax) ? fr : tmax;
	}
	if (tmin <= tmax)
	{
		return tmin;
	}
	return -1.0f;
}
float AABB2f::CollideWithSphere(Vec2f pos, float radius, Vec2f& outPos, Vec2f& outNormal)
{
	char inside = 0;
	for (int i=0; i<2; ++i)
	{
		if (pos[i] < min[i])
		{
			outPos[i] = min[i];
		}
		else if (pos[i] > max[i])
		{
			outPos[i] = max[i];
		}
		else
		{
			outPos[i] = pos[i];
			++inside;
		}
	}
	if (inside == 2)
	{
		outNormal = (pos - (min+max)*0.5f).Normalized();
		return radius;
	}
	else
	{
		Vec2f vdist = pos - outPos;
		float distance = vdist.Length();
		if (distance < radius)
		{
			outNormal = vdist / distance;
			return distance;
		}
	}

	return -1.0f;
}


} // Namespace